package com.cskaoyan.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author stone
 * @date 2021/11/22 17:35
 */
@Component
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String value) {
        String pattern = null;
        if (value.length() == 10 && value.contains("-")) {
            pattern = "yyyy-MM-dd";
        } else if (value.length() == 10) {
            pattern = "yyyy/MM/dd";
        } else if (value.length() == 19) {
            pattern = "yyyy/MM/dd HH:mm:ss";
        } else {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(value);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
